package com.durunmin;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerOne {

    public static void main(String[] args) throws IOException {

        ServerSocket serverSocket = new ServerSocket(2000);

        System.out.println("服务器准备就绪~");
        System.out.println("服务器信息："+serverSocket.getInetAddress()+" P: "+serverSocket.getLocalPort());
        System.out.println("服务器信息："+serverSocket.getLocalSocketAddress()+" P: "+serverSocket.getLocalPort());
        while (true){
            Socket socket = serverSocket.accept();
            ClientHandler clientHandler = new ClientHandler(socket);
            clientHandler.start();
        }

    }


    public static class ClientHandler extends Thread{

        private Socket socket;

        public ClientHandler(Socket socket){
            this.socket = socket;
        }

        @Override
        public void run() {
            super.run();
            System.out.println("新客户端连接："+socket.getInetAddress()+" P: "+socket.getPort());
            try {
                //获取输入流
                BufferedReader socketInput = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                //构建输出流
                PrintStream printStream = new PrintStream(socket.getOutputStream());

                boolean flag = true;
                while (flag){

                    String string = socketInput.readLine();
                    System.out.println("客户端信息："+string);
                    if ("bye".equals(string)){
                        flag = false;
                        printStream.println("bye");
                    } else {
                        printStream.println("回送："+string.length());
                    }

                }
                socketInput.close();
                printStream.close();

            } catch (IOException e) {
                System.out.println("连接异常断开");
                e.printStackTrace();
            }

            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            System.out.println("客户端已退出："+socket.getInetAddress()+" P: "+socket.getPort());


        }
    }
}
